package avicit.bdp.dgs.mdm.service;

import avicit.bdp.common.base.BaseService;
import avicit.bdp.common.utils.BdpLogUtil;
import avicit.bdp.common.utils.CheckParaUtils;
import avicit.bdp.dgs.mdm.dao.MdataLogDao;
import avicit.bdp.dgs.mdm.dto.MdataApplicationDTO;
import avicit.bdp.dgs.mdm.dto.MdataInterfaceDTO;
import avicit.bdp.dgs.mdm.dto.MdataLogDTO;
import avicit.bdp.dgs.mdm.utils.enums.CallStatus;
import avicit.platform6.commons.utils.ComUtil;
import avicit.platform6.commons.utils.PojoUtil;
import avicit.platform6.core.exception.BusinessException;
import avicit.platform6.core.exception.DaoException;
import avicit.platform6.core.properties.PlatformConstant;
import avicit.platform6.core.rest.msg.QueryRespBean;
import avicit.platform6.modules.system.syslog.service.SysLogUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @金航数码科技有限责任公司
 * @作者：${tableInfo.classCreator}
 * @邮箱：${tableInfo.classMailbox}
 * @创建时间： 2023-12-06 11:02
 * @类说明：
 * @修改记录：
 */
@Service
public class MdataLogService extends BaseService<MdataLogDao, MdataLogDTO> {

    private static final Logger logger = LoggerFactory.getLogger(MdataLogService.class);

    @Autowired
    private MdataLogDao mdataLogDao;
    @Autowired
    private MdataApplicationService mdataApplicationService;
    @Autowired
    private MdataInterfaceService mdataInterfaceService;

    /**
     * 分页查询
     * @param callStatus
     * @param pageNo
     * @param pageSize
     * @return
     * @throws Exception
     */
    @Transactional(readOnly = true)
    public QueryRespBean<MdataLogDTO> getPageList(Integer callStatus, Integer callbackStatus, String applicationId,
                                                  String interfaceId, Integer pageNo, Integer pageSize)
            throws Exception {
        QueryRespBean<MdataLogDTO> queryRespBean = new QueryRespBean<>();
        PageHelper.startPage(pageNo, pageSize);
        Page<MdataLogDTO> pageList = mdataLogDao.getPageList(callStatus, callbackStatus, applicationId, interfaceId);
        valueConvert(pageList.getResult());
        queryRespBean.setResult(pageList);
        BdpLogUtil.log4Query(queryRespBean);
        return queryRespBean;
    }

    private void valueConvert(List<MdataLogDTO> mdataLogList) {
        for (MdataLogDTO log : mdataLogList) {
            log.setCallStatusName(CallStatus.getDescByCode(log.getCallStatus()));
            log.setCallbackStatusName(CallStatus.getDescByCode(log.getCallbackStatus()));
        }
    }

    /**
     * 新增对象
     *
     * @param dto 保存对象
     * @return String
     */
    @Transactional
    public String save(MdataLogDTO dto) {
        try {
            dto.setId(ComUtil.getId());
            PojoUtil.setSysProperties(dto, PlatformConstant.OpType.insert);
            this.insert(dto);
            // 记录日志
            SysLogUtil.log4Insert(dto);
            return dto.getId();
        } catch (Exception e) {
            throw new DaoException(e.getMessage(), e);
        }
    }

    /**
     * 修改对象部分字段
     *
     * @param dto 修改对象
     * @return int
     */
    @Transactional
    public int update(MdataLogDTO dto) {
        try {
            int count = this.updateByPrimaryKey(getUpdateDto(dto));
            if (count == 0) {
                throw new DaoException("数据失效，请重新更新");
            }
            return count;
        } catch (Exception e) {
            throw new DaoException(e.getMessage(), e);
        }
    }

    /**
     * 通过主键查询单条记录
     *
     * @param id 主键id
     */
    @Transactional(readOnly = true)
    public MdataLogDTO queryById(String id) {
        try {
            MdataLogDTO dto = this.selectByPrimaryKey(id);
            CheckParaUtils.checkDbObjectValidity(dto, logger, String.format("没有查到数据，请确保id:%s的日志数据是否存在", id));
            MdataApplicationDTO applicationDTO = mdataApplicationService.selectByPrimaryKey(dto.getApplicationId());
            MdataInterfaceDTO interfaceDTO = mdataInterfaceService.selectByPrimaryKey(dto.getInterfaceId());

            if(applicationDTO != null){
                dto.setApplicationName(applicationDTO.getName());
            }
            if(interfaceDTO != null){
                dto.setInterfaceName(interfaceDTO.getName());
                dto.setInterfaceCode(interfaceDTO.getCode());
            }
            dto.setCallStatusName(CallStatus.getDescByCode(dto.getCallStatus()));
            dto.setCallbackStatusName(CallStatus.getDescByCode(dto.getCallbackStatus()));

            // 记录日志
            if (dto != null) {
                SysLogUtil.log4Query(dto);
            }
            return dto;
        } catch (Exception e) {
            throw new DaoException(e.getMessage(), e);
        }
    }

    /**
     * 删除
     */
    @Transactional
    public void deleteById(String id){
        if (StringUtils.isEmpty(id)) {
            throw new BusinessException("id不能为空");
        }

        MdataLogDTO dto = this.selectByPrimaryKey(id);
        if (dto == null) {
            throw new BusinessException(String.format("id=%s的应用不存在", id));
        }
        // 记录日志
        BdpLogUtil.log4Delete(dto);
        // 删除数据
        this.deleteByPrimaryKey(id);
    }

    /**
     * 内部方法，获取修改的dto对象
     *
     * @param dto
     * @return
     */
    private MdataLogDTO getUpdateDto(MdataLogDTO dto) {
        MdataLogDTO oldDTO = this.selectByPrimaryKey(dto.getId());
        if (oldDTO == null) {
            throw new DaoException("数据不存在");
        }
        //记录日志
        SysLogUtil.log4Update(dto, oldDTO);
        PojoUtil.setSysProperties(dto, PlatformConstant.OpType.update);
        PojoUtil.copyProperties(oldDTO, dto, true);
        return oldDTO;
    }

}
